//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <windows.h>
#include <stdio.h>
#include "send.h"
#include "DevicePower.h"

HANDLE hevent;
HANDLE hmmap;
HANDLE hmutex;
void Send_Initialize()
{
    hevent=CreateEvent(NULL,FALSE,FALSE,TEXT("DENTANCE_EVENT"));
    if (hevent == NULL) {
        if (GetLastError() == ERROR_ALREADY_EXISTS) {
            printf("event already exits - not created!\n");
            CloseHandle(hevent);
        }
    }
    hmmap=CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,sizeof(Device_Power)*MaxDevice,TEXT("DENTANCE_NEWMODE"));
    if (hmmap == NULL) {
        if (GetLastError() == ERROR_ALREADY_EXISTS) {
            printf("mapping already exits - not created!\n");
            CloseHandle(hmmap);
        }
    }
    hmutex=CreateMutex(NULL,FALSE,TEXT("DENTANCE_MUTEX"));
    if (hmmap == NULL) {
        if (GetLastError() == ERROR_ALREADY_EXISTS) {
            printf("mutex already exits - not created!\n");
            CloseHandle(hmutex);
        }
    }

    STARTUPINFO si={sizeof(si)};
    TCHAR CMD[]=TEXT("display");
    PROCESS_INFORMATION pi;
    if (!CreateProcess(NULL, CMD, NULL, NULL, FALSE, 0, NULL, NULL,&si,&pi)) {
        printf("creating process failed\n");
        exit(1);
    }
}

void Send(unsigned int frequency, float voltage)
{
    UINT * pmap=(UINT *)MapViewOfFile(hmmap,FILE_MAP_READ|FILE_MAP_WRITE,0,0,0);
    *pmap=frequency;
    *(float*)(++pmap)=voltage;
    SetEvent(hevent);
}

void Send_Cleanup()
{//send -1 to tell the displayer to eliminate it's execution.
    int * pmap=(int *)MapViewOfFile(hmmap,FILE_MAP_READ|FILE_MAP_WRITE,0,0,0);
    *pmap=-1;
    SetEvent(hevent);
}

void SendEx(void * pBuffer, int index)
{
    DWORD dw=WaitForSingleObject(hmutex,INFINITE);
    if (dw == WAIT_OBJECT_0) {
        Device_Power * pmap=(Device_Power*)MapViewOfFile(hmmap,FILE_MAP_READ|FILE_MAP_WRITE,0,0,0);
        pmap+=index;
        memcpy(pmap,pBuffer,sizeof(Device_Power));
        ReleaseMutex(hmutex);
    }
    SetEvent(hevent);//I don't know whether the event is needed.I think it is necessary
}
